var _INDEX = '0';
var _TYPE = 'MerchantWords:Search ET List';

function log(msg,level = config.LOG._LOG_LEVEL_DEBUG) {
    logger.out(`{${_TYPE} (index:${_INDEX})} ` + msg,level)
}

function parser() {
    let result = {
        rows :{
            list:[],
            cates:[]
        },
        code:Const._RETCODE_HANDLER_FAILED
    };
    //解析关键字列表
    result.rows.list = parserList();
    //解析类目列表
    result.rows.cates = parserCates();
    return result;
}

function parserCates() {
    let result = [];
    let list = $('#select-search-trends-categories > option');
    log(`Cates Length:${list.length}`);
    for(let i = 0; i < list.length; i++){
        let cateName = utils.special($(list[i]).text());
        let code = $(list[i]).attr('value');
        result.push({
            cateName:cateName,
            code:code
        })
    }
    return result;
}

function parserList() {
    let result = [];
    let list = $('body > div.wrapper.wrapper--search-login > div.competition-tool--landing-page.competition-tool--fs.main > section.section-call-out.section-call-out-first.fs.grey > div > div > div.row > div > div > div.table__body > table > tbody > tr');
    if(!list || list.length === 0){
        log(`Not Parser ET List.`);
        return result;
    }
    log(`ET List Length:${list.length}`);
    for(let i = 0; i < list.length; i++){
        let dom = list[i];
        //关键字列表
        let keywords = parseList(dom,i);
        //SEARCH VOLUME
        let volume = parserVolume(dom,i);
        //DEPTH
        let depth = parserDepth(dom,i);
        //APPEARANCE
        let appearance = parserAppearance(dom,i);
        result.push({
            keywords:keywords,
            volume:volume,
            depth:depth,
            appearance:appearance
        })
    }
    log(`ET List:${JSON.stringify(result)}`);
    return result;
}


function parserAppearance(dom,i) {
    let express = `tr:nth-child(${i + 1}) > td:nth-child(4)`;
    return $(dom).find(express).text();
}

function parserDepth(dom,i) {
    let express = `tr:nth-child(${i + 1}) > td:nth-child(3)`;
    return $(dom).find(express).text();
}

function parserVolume(dom,i) {
    let express = `tr:nth-child(${i + 1}) > td:nth-child(2)`;
    return $(dom).find(express).text();
}
/**
 * 获取关键字列表
 */
function parseList(dom,i) {
    let keywords = [];
    let express = `tr:nth-child(${i + 1}) > td:nth-child(1) > div > a`;
    let keywordsDom = $(dom).find(express);
    for(let j = 0; j < keywordsDom.length; j++){
        let keyword = $(keywordsDom[j]).text();
        keywords.push(keyword)
    }
    return keywords;
}

try {
    var $ = cheerio.load(htmlString);
    result = parser();
    if(result.rows.list.length > 0 && result.rows.cates.length > 0){
        result.code =Const._RETCODE_SUCCESS;
    }

    parserInfo.index = _INDEX;
    parserInfo.type = _TYPE;
} catch (e) {
    log(`Parsing Exception:${e.message}`,config.LOG._LOG_LEVEL_ERROR);
    result.code = Const._RETCODE_HANDLER_FAILED;
}

